import ReactCodeMirror from '@uiw/react-codemirror/esm';
import { Button, Card, ConfigProvider, Drawer, notification, Popover } from 'antd';

import { Table } from '@/components/base/Table';
import { useGraph } from '@/hooks/useGraph';
import { useDictStore } from '@/store/dict';
import { NodeResultItem, useNodeResults } from '@/store/node-results';
import { getAllVariables } from '@/utils/graph';

interface ExecLoggerDetailProps {
  nodeId: string;
  onClose: () => void;
  focusResult: NodeResultItem | null;
}

export const ExecLoggerDetail = memo<ExecLoggerDetailProps>((props) => {
  const resultsStore = useNodeResults();
  const { focusResult } = props;
  const { graph } = useGraph();
  const { systemVars } = useDictStore();

  const variables = useMemo(() => {
    const nodeVariables = getAllVariables(graph!, 'public') || [];
    const privateVariables = getAllVariables(graph!, 'private') || [];
    return privateVariables.concat(nodeVariables).concat(systemVars);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [graph, resultsStore.resultsOfList]);

  const reqTableColumns = useMemo(() => {
    return [
      {
        title: '参数中文名',
        dataIndex: 'varLabel'
      },
      {
        title: '参数名',
        dataIndex: 'varName'
      },
      {
        title: '参数值',
        dataIndex: 'value',
        render: (value: any) => {
          const isMore = typeof value === 'object' || value?.length > 200;
          if (isMore) {
            return (
              <Popover
                trigger="click"
                title="参数值详情"
                content={<ReactCodeMirror value={JSON.stringify(value, null, 2)} width="600px" height="350px" />}
                placement="left">
                <div className="text-14 text-primary-500 cursor-pointer">查看</div>
              </Popover>
            );
          }
          return value;
        }
      }
    ];
  }, []);

  const variableOfLabelMap = useMemo(() => {
    return variables.reduce(
      (prev: Record<string, any>, curr) => {
        prev[curr.varName!] = curr.varLabel || curr.varName;
        return prev;
      },
      {} as Record<string, string>
    );
  }, [variables]);

  // 提取入参
  const getParamsList = (params: Record<string, any>) => {
    return Object.keys(params).reduce((list, key) => {
      return list.concat({
        varLabel: variableOfLabelMap[key] || '-',
        varName: key,
        value: params[key]
      });
    }, [] as any[]);
  };

  const copyInputParams = (data: any) => {
    if (navigator.clipboard) {
      const params: Record<string, any> = Object.assign({}, data || {});
      navigator.clipboard.writeText(JSON.stringify(params, null, 2)).then(() => {
        notification.success({ message: '复制成功' });
      });
    }
  };

  return (
    <ConfigProvider componentDisabled={false}>
      <Drawer
        destroyOnClose
        width={1000}
        onClose={(e) => {
          props.onClose?.();
          e.stopPropagation();
        }}
        onClick={(e) => e.stopPropagation()}
        title={<div className="text-value-16_bold ">执行结果详情</div>}
        open={!!props.focusResult}>
        <div className="result-detail py-12 flex flex-col gap-20">
          {Boolean(focusResult?.errorMsg) && (
            <div className="text-14 pb-12 px-16">
              <span className="!text-gray-600 text-value-16_bold">失败原因：</span>
              <span className="text-14 !text-red">{focusResult?.errorMsg || '失败'}</span>
            </div>
          )}
          {focusResult?.execResult?.map((result, resultIndex) => {
            const reqList = getParamsList(result?.inputParams || {});
            const resList = result?.results || [];
            return (
              <Card size="small" key={resultIndex} title={<span className="text-primary-500">执行轮次：{resultIndex + 1}</span>}>
                <div className="px-16">
                  <div className="text-14 pb-12">
                    <span className="!text-gray-600 text-value-16_bold">执行结果：</span>
                    <span className="text-value-16 !text-green-500">成功</span>
                  </div>
                  {!!reqList?.length && (
                    <div className="input-params">
                      <div className="flex justify-between pb-8">
                        <span className="text-14--bold">节点入参</span>
                        <Button onClick={() => copyInputParams(result.inputParams)} type="text">
                          复制为JSON
                        </Button>
                      </div>
                      <Table rowKey="varName" pagination={false} columns={reqTableColumns} dataSource={reqList} />
                    </div>
                  )}

                  {!!resList?.length && (
                    <div className="output-params">
                      <div className="flex justify-between mt-20">
                        <span className="text-14--bold">节点返回的结果</span>
                      </div>
                      <ReactCodeMirror
                        width="896px"
                        height="370px"
                        className="border border-gray-200 border-solid mt-4"
                        value={JSON.stringify(resList, null, 2)}
                      />
                    </div>
                  )}
                </div>
              </Card>
            );
          })}
        </div>
      </Drawer>
    </ConfigProvider>
  );
});
